import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import HomeView from '@/views/home/HomePage.vue'
import LoginPage from '@/views/login.vue'
import Routes from './routes'
import { useAuthStore } from '@/stores/user-auth'
import DrawWaiting from '@/views/draw-waiting.vue'
import FeedDetail from '@/views/feed-detail/FeedDetail.vue'
import CreatePage from '@/views/create/CreatePage.vue'
import ResultPage from '@/views/result/ResultPage.vue'

const router = createRouter({
  // history: createWebHashHistory(import.meta.env.BASE_URL),
  history: createWebHistory(),
  scrollBehavior: (to, from, savedPosition) => {
    if (to.name !== Routes.home) {
      return { top: 0 }
    }
    if (savedPosition) {
      return savedPosition
    }
  },
  routes: [
    {
      path: '/',
      name: Routes.home,
      component: HomeView
    },
    {
      path: '/feed-detail',
      name: Routes.feedDetail,
      component: FeedDetail
    },
    {
      path: '/create',
      name: Routes.create,
      component: CreatePage
    },
    {
      path: '/login',
      name: Routes.login,
      component: LoginPage
    },
    {
      path: '/draw/result',
      name: Routes.drawResult,
      meta: { requiresAuth: true },
      component: ResultPage
    },
    {
      path: '/:catchAll(.*)',
      name: '404',
      component: () => import('@/views/404.vue')
    }
  ]
})

router.beforeEach((to, from) => {
  const meta = to.meta
  const authStore = useAuthStore()
  if (meta.requiresAuth && !authStore.isAuthorized) {
    return { name: Routes.login }
  }
  return true
})

export default router
